import { Button, message, Popconfirm, Spin, Tree } from 'antd';
import React, { useEffect, useState } from 'react';
import { addMenu, deleteMenu, listMenu, updateMenu } from './service';
import type { addFile, RootObject } from './data';
import Styles from './index.less';
import TreeTag from '@/components/TreeTag';
import { ModalForm, PageContainer, ProFormSelect, ProFormText } from '@ant-design/pro-components';

/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields: addFile) => {
    const hide = message.loading('正在添加');
    try {
        await addMenu({ ...fields });
        hide();
        message.success('添加成功');
        return true;
    } catch (error) {
        hide();
        return false;
    }
};
/**
 * 更新节点
 *
 * @param fields
 */

const handleUpdate = async (fields: any, currentRow?: RootObject) => {
    const hide = message.loading('正在修改');

    try {
        await updateMenu({
            ...currentRow,
            ...fields,
        });
        hide();
        message.success('修改成功');
        return true;
    } catch (error) {
        hide();
        return false;
    }
};

const TableList: React.FC = () => {
    /** 新建窗口的弹窗 */
    const [createModalVisible, handleModalVisible] = useState<boolean>(false);

    const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);

    const [loading, setLoading] = useState<boolean>(false);
    const [info, setInfo] = useState<boolean>(false);
    const [currentRow, setCurrentRow] = useState<RootObject | null>();
    const [treeData, setTreeData] = useState<RootObject[]>([]);

    // 添加和编辑相同部分表单
    const editAndAddFrom = () => (
        <>
            <ProFormText
                rules={[
                    {
                        required: true,
                        message: '该项为必填项',
                    },
                ]}
                width="md"
                name="name"
                disabled={info}
                label={`名称`}
            />
            <ProFormSelect
                name="type"
                label="类型"
                width="md"
                disabled={info}
                valueEnum={{
                    1: '页面',
                    2: '动作',
                    3: '平台',
                    4: '模块',
                }}
                rules={[{ required: true, message: '该选项为必填' }]}
            />
            <ProFormText
                rules={[
                    {
                        required: true,
                        message: '该项为必填项',
                    },
                ]}
                width="md"
                name="url"
                disabled={info}
                label={`地址/操作`}
            />
        </>
    );

    /**
     * 获取数据
     */
    const getData = async () => {
        setLoading(true);
        const res = await listMenu({ tree: true });
        setTreeData(res);
        setLoading(false);
    };

    useEffect(() => {
        getData();
    }, []);

    /**
     * 添加点击
     */
    const addClickHandle = () => {
        setCurrentRow(null);
        handleModalVisible(true);
    };

    return (
        <PageContainer
            header={{
                extra: [
                    <Button key="add" type="primary" onClick={addClickHandle}>
                        新建根节点
                    </Button>,
                ],
            }}
        >
            <Spin spinning={loading}>
                {treeData.length > 0 && (
                    <Tree
                        blockNode
                        defaultExpandAll
                        fieldNames={{ key: 'guid', title: 'name' }}
                        titleRender={(data: RootObject) => {
                            return (
                                <div key={data.id} className={Styles.treeItem}>
                                    <TreeTag title={data?.name} type={data?.type} />
                                    <div>
                                        <Button
                                            type="text"
                                            onClick={(event) => {
                                                event.stopPropagation();
                                                setCurrentRow(data);
                                                setInfo(true);
                                                handleUpdateModalVisible(true);
                                            }}
                                        >
                                            详情
                                        </Button>
                                        <Button
                                            type="link"
                                            onClick={(event) => {
                                                event.stopPropagation();
                                                setCurrentRow(data);
                                                handleModalVisible(true);
                                            }}
                                        >
                                            添加子节点
                                        </Button>
                                        <Button
                                            type="link"
                                            onClick={(event) => {
                                                event.stopPropagation();
                                                setCurrentRow(data);
                                                handleUpdateModalVisible(true);
                                            }}
                                        >
                                            编辑
                                        </Button>
                                        <Popconfirm
                                            title="是否确认删除？"
                                            onConfirm={async () => {
                                                const hide = message.loading('正在删除');
                                                try {
                                                    await deleteMenu({
                                                        guid: data.guid,
                                                    });
                                                    hide();
                                                    message.success('删除成功');
                                                    getData();
                                                    return true;
                                                } catch (error) {
                                                    hide();
                                                    return false;
                                                }
                                            }}
                                            okText="确认"
                                            cancelText="取消"
                                        >
                                            <Button type="link" danger>
                                                删除
                                            </Button>
                                        </Popconfirm>
                                    </div>
                                </div>
                            );
                        }}
                        treeData={treeData}
                    />
                )}
            </Spin>

            <ModalForm
                title="新建"
                width="600px"
                visible={createModalVisible}
                onVisibleChange={handleModalVisible}
                onFinish={async (value: { name: string; type: number; url: string }) => {
                    let pid: number = "0";
                    if (currentRow) {
                        pid = currentRow.guid || '0';
                    }
                    const success = await handleAdd({ pid, ...value });
                    if (success) {
                        handleModalVisible(false);
                        setCurrentRow(null);
                        getData();
                    }
                }}
                modalProps={{
                    destroyOnClose: true,
                }}
                initialValues={{
                    pname: currentRow?.name,
                    purl: currentRow?.url,
                }}
            >
                {currentRow && (
                    <>
                        <ProFormText disabled width="md" name="pname" label={`父菜单名称`} />
                        <ProFormText disabled width="md" name="purl" label={`父地址`} />
                    </>
                )}
                {editAndAddFrom()}
            </ModalForm>

            <ModalForm
                title={info ? '详情' : '编辑'}
                width="600px"
                visible={updateModalVisible}
                onVisibleChange={(value) => {
                    !value && setInfo(false);
                    handleUpdateModalVisible(value);
                }}
                submitter={{
                    render: (props, defaultDoms) => {
                        return info ? [] : [
                            ...defaultDoms
                        ];
                    },
                }}
                onFinish={async (value) => {
                    const success = await handleUpdate({ guid: currentRow?.guid, ...value });
                    if (success) {
                        handleUpdateModalVisible(false);
                        setCurrentRow(null);
                        getData();
                    }
                }}
                modalProps={{
                    destroyOnClose: true,
                }}
                initialValues={{
                    name: currentRow?.name,
                    type: currentRow?.type + '', // 转为字符串
                    url: currentRow?.url,
                }}
            >
                {editAndAddFrom()}
            </ModalForm>
        </PageContainer>
    );
};

export default TableList;
